package com.iteye.weimingtom.cimmod;

import java.util.ArrayList;
import java.util.List;

public class TokenManager {
	private static TokenManager instance = new TokenManager();
	public static TokenManager getInstance() {
		return instance;
	}
	
	
	public List<TokenInfo> tokenList = new ArrayList<TokenInfo>();
	
	public TokenManager() {
		
	}
	
	public int getTotalToken() {
		checkTimeout();
		return tokenList.size();
	}

	public int getTotalAliveToken() {
		checkTimeout();
		int result = 0;
		for (TokenInfo tk : tokenList) {
			if (tk.getToken() != null && tk.getAlive() == 1) {
				result++;
			}
		}
		return result;
	}	
	
	public boolean contains(String token) {
		checkTimeout();
		boolean result = false;
		for (TokenInfo tk : tokenList) {
			if (tk.getToken() != null && tk.getAlive() == 1 && tk.getToken().equals(token)) {
				result = true;
				break;
			}
		}
		return result;
	}

	public void refresh(String token) {
		checkTimeout();
		for (TokenInfo tk : tokenList) {
			if (tk.getToken() != null && tk.getToken().equals(token)) {
				tk.setAlive(1);
				tk.setRefreshTime(System.currentTimeMillis());
				break;
			}
		}
	}	
	
	private void checkTimeout() {
		List<TokenInfo> removeList = new ArrayList<TokenInfo>();
		for (TokenInfo tk : tokenList) {
			if (tk.getToken() != null && tk.getAlive() == 1 && System.currentTimeMillis() - tk.getRefreshTime() > 1000 * 10) {
				removeList.add(tk);
			}
		}
		for (TokenInfo tk2 : removeList) {
			tk2.setAlive(0);
			tk2.setCloseTime(System.currentTimeMillis());
			//tokenList.remove(tk2);
		}
	}
	
	public void insert(String token) {
		checkTimeout();
		if (!contains(token)) {
			TokenInfo tk = new TokenInfo();
			tk.setToken(token);
			long now = System.currentTimeMillis();
			tk.setCreateTime(now);
			tk.setRefreshTime(now);
			tk.setAlive(1);
			tokenList.add(tk);
		}
	}
	
	public boolean login(String token, String username) {
		checkTimeout();
		boolean result = false;
		for (TokenInfo tk : tokenList) {
			if (tk.getToken() != null && tk.getAlive() == 1 && tk.getToken().equals(token)) {
				if (tk.getUsername() == null || tk.getUsername().equals("") || !tk.getUsername().equals(tk.getUsername())) {
					tk.setUsername(username);
					result = true;
				}
				break;
			}
		}
		return result;
	}
}
